# application/service/communication_service.py
import serial
import socket
import struct
from pymodbus.client import ModbusSerialClient, ModbusTcpClient


class CommunicationService:

    # 保存串口对象
    ser = None

    @staticmethod
    def connect_serial(data):
        """
        测试串口通讯
        """
        port = data.get("serialPort")
        baudrate = data.get("baudrate")

        if CommunicationService.ser and CommunicationService.ser.is_open:
            print("串口已连接，请勿重复连接")
            return True

        CommunicationService.ser = serial.Serial(port, baudrate, timeout=3)
        if CommunicationService.ser.is_open:
            return True

    @staticmethod
    def close_serial():
        """
        测试串口通讯
        """
        print("关闭串口连接")
        CommunicationService.ser.close()
        return True

    @staticmethod
    def send_serial_data(data):
        """
        发送串口数据
        """
        if not CommunicationService.ser or not CommunicationService.ser.is_open:
            print("串口未连接，请先连接串口")
            return False

        # 这里都会转成字节流发送
        dataCode = data.get("dataCode")
        sendOrder = data.get("sendOrder")

        if dataCode == "1":
            send_data = sendOrder.encode("ascii")
        elif dataCode == "2":
            hex_string = sendOrder.replace(" ", "")
            send_data = bytes.fromhex(hex_string)

        print(f"发送数据：{send_data}")
        CommunicationService.ser.write(send_data)
        return send_data

    @staticmethod
    def test_tcp_communication(host, port, message="PING"):
        """
        测试TCP通讯
        """
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(5)
            sock.connect((host, port))
            sock.send(message.encode())
            response = sock.recv(1024)
            sock.close()
            return {
                "success": True,
                "message": "TCP communication test successful",
                "response": (
                    response.decode("utf-8", errors="ignore") if response else ""
                ),
            }
        except Exception as e:
            return {
                "success": False,
                "message": f"TCP communication test failed: {str(e)}",
            }

    @staticmethod
    def test_modbus_communication(method, **kwargs):
        """
        测试Modbus通讯
        method: 'rtu' 或 'tcp'
        """
        try:
            if method == "rtu":
                client = ModbusSerialClient(
                    port=kwargs.get("port"),
                    baudrate=kwargs.get("baudrate", 9600),
                    parity=kwargs.get("parity", "N"),
                    stopbits=kwargs.get("stopbits", 1),
                    bytesize=kwargs.get("bytesize", 8),
                )
            elif method == "tcp":
                client = ModbusTcpClient(
                    host=kwargs.get("host"), port=kwargs.get("port", 502)
                )
            else:
                return {"success": False, "message": "Unsupported Modbus method"}

            client.connect()
            # 读取保持寄存器测试
            result = client.read_holding_registers(address=0, count=1, slave=1)
            client.close()

            if not result.isError():
                return {
                    "success": True,
                    "message": "Modbus communication test successful",
                    "response": str(result.registers),
                }
            else:
                return {
                    "success": False,
                    "message": "Modbus communication test failed: Device response error",
                }
        except Exception as e:
            return {
                "success": False,
                "message": f"Modbus communication test failed: {str(e)}",
            }

    # @staticmethod
    # def test_bluetooth_communication(address, port=1):
    #     """
    #     测试蓝牙通讯
    #     """
    #     try:
    #         sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    #         sock.connect((address, port))
    #         sock.send("PING")
    #         response = sock.recv(1024)
    #         sock.close()
    #         return {
    #             'success': True,
    #             'message': 'Bluetooth communication test successful',
    #             'response': response.decode('utf-8', errors='ignore') if response else ''
    #         }
    #     except Exception as e:
    #         return {
    #             'success': False,
    #             'message': f'Bluetooth communication test failed: {str(e)}'
    #         }
